package com.vip.mvc.utils.http;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Devin.Hu
 * @version V1.0
 * @date 2011-6-24
 * @description HttpClientUtils工具类，用于与服务端建立连接，传送或读取数据
 */
public class HttpClientUtils {

    private static final String _127_0_0_1 = "127.0.0.1";
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    public final static String DEFAULT_CHARSET = "UTF-8";
    public static final int DEFAULT_TIMEOUT = 5;
    public static final int DEFAULT_CONNECTION_TIMEOUT = 1000;
    public static final int DEFAULT_SOCKET_TIMEOUT = DEFAULT_TIMEOUT * 1000;
    public static final ThreadLocal<String> ip_session = new ThreadLocal<String>();
    private static PoolingClientConnectionManager cm = null;

    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
                .getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
                .getSocketFactory()));// TODO should we support https?
        cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(3000);
        cm.setDefaultMaxPerRoute(450);
    }

    /**
     * 得到HttpClient方法
     *
     * @return
     */

    public static HttpClient getHttpClient(int timeOut) {
        HttpParams httpParams = new BasicHttpParams();

        // 连接建立时的毫秒级超时时间
        HttpConnectionParams.setConnectionTimeout(httpParams,
                DEFAULT_CONNECTION_TIMEOUT);
        // 套接字的毫秒级超时时间 请求超时
        HttpConnectionParams.setSoTimeout(httpParams,
                timeOut > 0 ? timeOut * 1000 : DEFAULT_SOCKET_TIMEOUT);
        HttpConnectionParams.setSocketBufferSize(httpParams, 8192);

        HttpClientParams.setRedirecting(httpParams, true);

        String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";
        HttpProtocolParams.setUserAgent(httpParams, userAgent);

        // return new DefaultHttpClient(httpParams);
        // 通过连接池返回
        DefaultHttpClient httpClient = new DefaultHttpClient(cm, httpParams);
        // logConnectionStats();
        return httpClient;
    }

    /**
     * 执行doGet方法
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        // 使用工具默认编码
        return doGet(url, DEFAULT_CHARSET);
    }

    public static String doGet(String url, String charset) throws Exception {
        return doGet(url, charset, DEFAULT_TIMEOUT);
    }


    private static boolean isSuccess(int respStatusCode) {
        if (respStatusCode == HttpStatus.SC_OK
                || respStatusCode == HttpStatus.SC_CREATED) {
            return true;
        } else {
            return false;
        }
    }

    public static String doGet(String url, String charset, int timeout)
            throws Exception {

        return doGetUtils(url, charset, timeout, true);
    }


    public static String doGetUtils(String url, String charset, int timeout, boolean printRequestLog)
            throws Exception {
        String strResult = "";
        HttpResponse httpResponse = null;
        HttpClient httpClient = null;
        HttpGet httpRequest = null;
        /* 发送请求并等待响应 */
        try {
            httpClient = getHttpClient(timeout);
            httpRequest = new HttpGet(url);

            updateCommonHeader(httpRequest);
            httpResponse = httpClient.execute(httpRequest);
            // 查看响应状态 如果不是正常状态 则主动abort请求并返回
            if (isSuccess(httpResponse.getStatusLine().getStatusCode()) == false) {
                httpRequest.abort();
                logger.warn("target return error status, the url is :" + url);
                return null;
            }
            if (httpResponse.getEntity() != null) {
                byte[] bytes = getResponseEntityAsByteArray(httpResponse);
                strResult = new String(bytes, charset);
                strResult = filterHtml(strResult);
            }
        } catch (Exception e) {
            logger.error("http get error with url " + url, e);
            if (httpRequest != null) {
                httpRequest.abort();
            }
            throw e;
        }
        return strResult;
    }


    private static void updateCommonHeader(HttpRequestBase httpRequest) {
        httpRequest.addHeader("Referer", "http://apps-show.api.vip.com/");
        httpRequest.addHeader("Accept-Encoding", "gzip, deflate");

        // 请求参数增加客户端ip
        populateRequestIp(httpRequest);
    }

    private static void populateRequestIp(HttpRequestBase httpRequest) {
        // 增加IP转发功能
        String client_id = ip_session.get();
        if (StringUtils.isEmpty(client_id)) {
            client_id = _127_0_0_1;
        }
        httpRequest.setHeader("X-Forwarded-For", client_id);
        if (logger.isDebugEnabled()) {
            logger.debug(">>>> request ip: " + client_id);
        }
    }

    /**
     * 过滤特殊字符
     *
     * @param result
     * @return
     */
    private static String filterHtml(String result) {
        if (null != result) {
            result = result.replace("&#039;", "'");
            result = result.replace("&amp;", "&");
            result = result.replace("&nbsp;", " ");
        }
        return result;
    }

    /**
     * post request without parameters
     *
     * @param url
     * @return
     */
    public static String doPost(String url) {
        return doPost(url, DEFAULT_CHARSET, null);
    }

    // // 判断网络类型
    // public static boolean isWap() {
    // String proxyHost = android.net.Proxy.getDefaultHost();
    // if (proxyHost != null) {
    // return true;
    // } else {
    // return false;
    // }
    // }

    /**
     * post request by specified url & parameters
     *
     * @param url
     * @param map
     * @return
     */
    public static String doPost(String url, Map<String, Object> map) {
        return doPost(url, DEFAULT_CHARSET, map);
    }

    /**
     * post request by specified url, charset & parameters
     *
     * @param url
     * @param charset
     * @param map
     * @return
     */
    public static String doPost(String url, String charset,
                                Map<String, Object> map) {
        return doPost(url, charset, map, DEFAULT_TIMEOUT);
    }

    public static String doPost(String url, String content, String charset,
                                int timeout) {
        if (logger.isInfoEnabled())
            logger.info("post url: " + url + " with content " + content);// 这个日志重复，但是此方法没有地方调用，暂不理会
        HttpClient httpClient = getHttpClient(timeout);
        HttpPost httpRequest = new HttpPost(url);
        httpRequest.addHeader("Referer", "http://apps-show.api.vip.com/");
        // HttpEntity repEntity = null;
        try {
            HttpEntity repEntity = new StringEntity(content, charset);
            httpRequest.setEntity(repEntity);
            return doPost(httpClient, httpRequest);
        } catch (UnsupportedEncodingException e) {
            logger.error("specified " + content + " convert to " + charset
                    + " error", e);
        } catch (Exception e) {
            logger.error("post to " + url + " with content " + content, e);
        } finally {
            // request entity not contain input stream
            /*
             * try { if (repEntity != null) { EntityUtils.consume(repEntity); }
			 * } catch (IOException e) {
			 * logger.error(" final consume the stream ", e); }
			 */
        }
        return null;
    }

    public static String doPost(String url, String charset,
                                Map<String, Object> parameters, int timeout) {
        return doPost(url, charset, parameters, timeout, null);
    }

    public static String doPost(String url, String charset,
                                Map<String, Object> parameters, int timeout,
                                Map<String, String> headerMap) {

        HttpClient httpClient = getHttpClient(timeout);
        HttpPost httpRequest = new HttpPost(url);
        httpRequest.addHeader("Referer", "http://apps-show.api.vip.com/");
        // set request parameters
        if (parameters != null && !parameters.isEmpty()) {
            List<NameValuePair> params = new ArrayList<NameValuePair>(
                    parameters.size());
            for (String key : parameters.keySet()) {
                params.add(new BasicNameValuePair(key, String
                        .valueOf(parameters.get(key))));
            }
            try {
                httpRequest.setEntity(new UrlEncodedFormEntity(params,
                        DEFAULT_CHARSET));
            } catch (UnsupportedEncodingException e) {
                logger.warn("set parameter error ", e);
            }
        }

        // set request headers
        addHeaderForHttpRequestBase(httpRequest, headerMap);

        try {
            return doPost(httpClient, httpRequest);
        } catch (Exception e) {
            logger.warn("异常！", e);
        }

        return null;
    }

    public static String doPost(HttpClient httpClient,
                                HttpEntityEnclosingRequestBase httpRequest) throws Exception {
        HttpEntity rspEntity = null;
        try {
            long start = System.currentTimeMillis();

            // specify some common header, like IP, reference, accept
            updateCommonHeader(httpRequest);

            HttpResponse httpResponse = httpClient.execute(httpRequest);
            if (isSuccess(httpResponse.getStatusLine().getStatusCode())) {
                rspEntity = httpResponse.getEntity();
                if (rspEntity != null) {
                    byte[] bytes = getResponseEntityAsByteArray(httpResponse);

                    if (logger.isInfoEnabled()) {
                        String responseMinStr = logHttpRespone(bytes,
                                DEFAULT_CHARSET);
                        logger.info("HTTP POST : " + (httpRequest.getURI())
                                + ", Response is [" + responseMinStr
                                + "], Length is ["
                                + (bytes != null ? bytes.length : 0) + "]");
                    }
                    return new String(bytes, DEFAULT_CHARSET);
                }
            } else {
                // 查看响应状态 如果不是正常状态 则主动abort请求并返回{
                logger.warn("target return error status, the url is :"
                        + httpRequest.getURI());
                rspEntity = httpResponse.getEntity();

                if (rspEntity != null) {
                    logger.warn("target return error message, the data is :"
                            + EntityUtils.toString(rspEntity, DEFAULT_CHARSET));
                }
                httpRequest.abort();
                return null;
            }
        } catch (Exception e) {
            httpRequest.abort();
            throw e;
        } finally {
            try {
                if (rspEntity != null) {
                    EntityUtils.consume(rspEntity);
                }
            } catch (IOException e) {
                logger.error(" final consume the stream ", e);
            }
        }
        return null;
    }

    private static byte[] getResponseEntityAsByteArray(HttpResponse httpResponse)
            throws IOException {
        Header contentEncodingHeader = httpResponse
                .getFirstHeader("Content-Encoding");
        byte[] bytes = null;
        if (contentEncodingHeader != null
                && contentEncodingHeader.getValue().toLowerCase()
                .indexOf("gzip") > -1) {
            bytes = EntityUtils.toByteArray(new GzipDecompressingEntity(
                    httpResponse.getEntity()));
        } else {
            bytes = EntityUtils.toByteArray(httpResponse.getEntity());
        }
        return bytes;
    }

    /**
     * add headers for HttpRequestBase
     *
     * @param httpRequest
     * @param headerMap
     */
    private static void addHeaderForHttpRequestBase(
            HttpRequestBase httpRequest, Map<String, String> headerMap) {
        if (headerMap != null && !headerMap.isEmpty()) {
            for (String key : headerMap.keySet()) {
                httpRequest.addHeader(key, headerMap.get(key));
            }
        }
    }

    /**
     * 打印HTTP的响应
     *
     * @author jame.xu
     * @date 2014-4-3
     * @description
     * @mail jame.xu@vipshop.com
     */
    private static String logHttpRespone(byte[] data, String charset) {
        if (data != null && data.length > 0) {
            int length = data.length >= 16 ? 16 : data.length;
            byte[] dest = new byte[length];
            System.arraycopy(data, 0, dest, 0, length);
            try {
                String result = new String(dest, charset);
                if (null != result) {
                    result = result.replace("\r\n", " ");
                    return result;
                }
            } catch (UnsupportedEncodingException e) {
            }
        }
        return null;
    }


}
